<template>
	<div class="app-container">
		<!-- 查询和其他操作 -->
		<div class="filter-container">
			<!--<el-input v-model="listQuery.cateName" clearable class="filter-item" style="width: 200px;"-->
			<!--          placeholder="请输入类目名称"/>-->
			<el-select v-model="listQuery.cateLevel" clearable style="width: 200px" class="filter-item"
			           placeholder="请选择类目级别">
				<el-option v-for="(key, value) in categoryLevelMap" :key="key" :label="key" :value="value"/>
			</el-select>
			<el-button v-permission="[1]" class="filter-item" type="primary" icon="el-icon-search"
			           @click="handleFilter">查找
			</el-button>
			<el-button v-permission="[1]" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
				添加
			</el-button>
		</div>

		<!-- 查询结果 -->
		<el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中。。。" border fit
		          highlight-current-row>

			<el-table-column align="center" width="160" label="操作">
				<template slot-scope="scope">
					<el-button v-permission="[1]" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑
					</el-button>
					<el-button v-permission="[1]" type="warning" size="mini" @click="handleDelete(scope.row)">删除
					</el-button>
				</template>
			</el-table-column>

			<el-table-column align="center" width="80" label="类目ID" prop="id"/>

			<el-table-column align="center" label="名称" prop="name"/>


			<el-table-column align="center" width="100" label="一级类目ID" prop="category1Id"/>
			<el-table-column align="center" width="100" label="二级类目ID" prop="category2Id"/>

			<el-table-column align="center" width="100" label="级别">
				<template slot-scope="scope">
					<div v-if="scope.row.category2Id">
						<el-tag>三级类目</el-tag>
					</div>
					<div v-else-if="scope.row.category1Id">
						<el-tag>二级类目</el-tag>
					</div>
					<div v-else>
						<el-tag>一级类目</el-tag>
					</div>
				</template>
			</el-table-column>

			<el-table-column align="center" label="类目图片" prop="picture">
				<template slot-scope="scope">
					<img v-if="scope.row.picture" :src="scope.row.picture" width="80">
				</template>
			</el-table-column>

		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
		            @pagination="getList"/>

		<!-- 添加或修改对话框 -->
		<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
			<el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left"
			         label-width="100px" style="width: 400px; margin-left:50px;">
				<el-form-item label="类目ID" prop="id" hidden>
					<el-input v-model="dataForm.id"/>
				</el-form-item>
				<el-form-item label="类目名称" prop="name">
					<el-input v-model="dataForm.name"/>
				</el-form-item>
				<el-form-item label="类目图片" prop="picture">
					<el-upload :action="uploadPath" :show-file-list="false"
					           :on-success="pirUploadSuccessHandle" :before-upload="onBeforeUpload"
					           class="avatar-uploader" accept=".jpg, .jpeg, .png, .gif">
						<img v-if="dataForm.picture" ref="adImg" :src="dataForm.picture" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"/>
					</el-upload>
				</el-form-item>

				<el-form-item label="父类目">
					<el-cascader :options="dialogOptions" :props="{ checkStrictly: true }" placeholder="选择父类目" clearable
					             filterable @change="handleLink"/>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取消</el-button>
				<el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
				<el-button v-else type="primary" @click="updateData">确定</el-button>
			</div>
		</el-dialog>
	</div>
</template>


<script>
	import {listCategory, categoryTree, createCategory, updateCategory, deleteCategory} from '@/api/category'
	import {uploadPath} from '@/api/storage'
	import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

	const categoryLevelMap = {
		1: '一级菜单',
		2: '二级菜单',
		3: '三级菜单'
	}
	export default {
		name: 'Category',
		components: {Pagination},
		filters: {
			categoryLevelFilter(code) {
				if (code >= 0 && code < 3) {
					return categoryLevelMap[code]
				}
				return '一级菜单'
			}
		},
		data() {
			return {
				uploadPath,
				list: undefined,
				total: 0,
				listLoading: true,
				dialogOptions: undefined,
				queryOptions: undefined,
				listQuery: {
					pageNum: 1,
					pageSize: 20,
					cateName: undefined,
					cateLevel: undefined
				},
				catL1: {},
				dataForm: {
					id: undefined,
					name: undefined,
					level: 1,
					picture: 'https://legouxiang.oss-cn-beijing.aliyuncs.com/mall/images/275c4a64ef424bbb9133d142a1d96f6c.png'
				},
				dialogFormVisible: false,
				dialogStatus: '',
				textMap: {
					update: '编辑',
					create: '创建'
				},
				rules: {
					name: [{required: true, message: '类目名不能为空', trigger: 'blur'}]
				},
				downloadLoading: false,
				categoryLevelMap

			}
		},
		created() {
			this.getList()
		},
		methods: {
			getList() {
				this.listLoading = true
				listCategory(this.listQuery, this.listQuery.cateLevel)
					.then(res => {
						this.list = res.data.records
						this.total = res.data.total
						this.listLoading = false
					})
					.catch(() => {
						this.list = []
						this.total = 0
						this.listLoading = false
					})
			},
			handleFilter() {
				this.listQuery.pageNum = 1
				this.getList()
			},
			resetForm() {
				this.dataForm = {
					id: undefined,
					name: undefined,
					picture: undefined
				}
			},
			resetQuery() {
				this.listQuery = {
					pageNum: 1,
					pageSize: 20,
					cateName: undefined
				}
			},
			handleCreate() {
				this.resetForm()
				this.dialogStatus = 'create'
				this.refreshCategoryOptions()
				this.queryOptions = undefined
				this.resetQuery()
				this.dialogFormVisible = true
				this.$nextTick(() => {
					this.$refs['dataForm'].clearValidate()
				})
			},
			createData() {
				this.$refs['dataForm'].validate(valid => {
					createCategory(this.dataForm, this.dataForm.level)
						.then(response => {
							this.getList()
							this.dialogFormVisible = false
							this.$notify.success({
								title: '成功',
								message: '创建成功'
							})
						})
						.catch(res => {
							this.$notify.error({
								title: '失败',
								message: res
							})
						})
				})
			},
			handleUpdate(row) {
				this.dataForm = Object.assign(this.dataForm, {
					id: row.id,
					name: row.name,
					level: row.level,
					picture: row.picture
				})
				this.refreshCategoryOptions()
				this.dialogStatus = 'update'
				this.dialogFormVisible = true
				this.$nextTick(() => {
					this.$refs['dataForm'].clearValidate()
				})
			},
			updateData() {
				this.$refs['dataForm'].validate(valid => {
					if (valid) {
						updateCategory(this.dataForm, this.dataForm.level)
							.then(() => {
								this.getList()
								this.dialogFormVisible = false
								this.$notify.success({
									title: '成功',
									message: '更新成功'
								})
							})
							.catch(res => {
								this.$notify.error({
									title: '失败',
									message: res
								})
							})
					}
				})
			},
			// 删除时使用
			handleDelete(row) {
				this.$confirm('此操作将永久删除该类目--' + row.name + '--, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					deleteCategory(row.id, this.listQuery.cateLevel)
						.then(res => {
							this.$notify.success({
								title: '成功',
								message: '删除成功'
							})
							const index = this.list.indexOf(row)
							this.list.splice(index, 1)
						})
						.catch(res => {
							this.$notify.error({
								title: '失败',
								message: res
							})
						})
				}).catch(() => {
					return false
				})
			},
			// 上传图片前调用
			onBeforeUpload(file) {
				const isIMAGE = file.type === 'image/jpeg' || 'image/gif' || 'image/png' || 'image/jpg'
				const isLt1M = file.size / 1024 / 1024 < 1

				if (!isIMAGE) {
					this.$message.error('上传文件只能是图片格式!')
				}
				if (!isLt1M) {
					this.$message.error('上传文件大小不能超过 1MB!')
				}
				return isIMAGE && isLt1M
			},
			// pir上传图片了处理图片
			pirUploadSuccessHandle(e) {
				this.dataForm.picture = e.data.photos
			},
			pirUploadRemoveHandle() {
				this.dataForm.picture = undefined
			},
			refreshCategoryOptions() {
				categoryTree().then(res => {
					res.data.forEach(item => {
						let obj1 = {
							value: item.id,
							label: item.name,
							children: []
						}
						if (item.twoList.length > 0) {
							item.twoList.forEach(twoList => {
								let obj2 = {
									value: item.id + ',' + twoList.id,
									label: twoList.name
								}
								obj1.children.push(obj2)
							})
						}
						this.dialogOptions.push(obj1)
					})
				})
				console.log(this.dialogOptions)
			},
			// 填写弹框选择父类目时，获得父类目的id
			handleLink(e) {
				if (e !== undefined) {
					const tag = e[e.length - 1]
					switch (e.length) {
						case 1:
							this.dataForm.category1Id = tag
							this.dataForm.level = 2
							break
						case 2:
							this.dataForm.category1Id = tag.split(',')[0]
							this.dataForm.category2Id = tag.split(',')[1]
							this.dataForm.level = 3
							break
					}
				} else {
					this.dataForm.category1Id = undefined
					this.dataForm.category2Id = undefined
					this.dataForm.level = 1
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #20a0ff;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 120px;
		height: 120px;
		line-height: 120px;
		text-align: center;
	}

	.avatar {
		width: 145px;
		height: 145px;
		display: block;
	}
</style>
